#!/usr/bin/env python
#coding=utf-8
import os, sys
import glob
import fnmatch
import numpy as np
import pandas as pd
import matplotlib.pylab as plt
import matplotlib.dates as mdate
import datetime
from matplotlib.font_manager import FontProperties  # 导入FontProperties

######################################
# 使用方法：
# python plot_temp temp_data_dir
######################################

def get_timestamp(date):
    return datetime.datetime.strptime(date,"%Y-%m-%d %H:%M:%S").timestamp()

# 设置中文字体显示
font = FontProperties(fname="/data2/data/05_正样温度数据/SimHei.ttf", size=14)  # 设置字体


def get_TempFiles(dirname):
    pattern = '*.txt'
    flist = []
    for r, d, f in os.walk(dirname):
        matches = fnmatch.filter(f, pattern)
        for m in matches:
            flist.append('{}/{}'.format(r,m))
    flist = np.unique(flist)

    if len(flist) == 0:
        raise Exception("len(flist) is zero.")

    return flist

def read_temp_data_from_dir(dirname, delimiter='\t', encoding='utf-8'):
    flist = get_TempFiles(dirname)
    dates = []
    data = []
    cnt = 0
    for f in flist:
        print('--> loading temperature data from : {}'.format(f))
        dates_tmp, data_tmp = read_temp_data_from_file(f, delimiter=delimiter, encoding=encoding)
        for i in range(len(dates_tmp)):
            dates.append(dates_tmp[i])
            data.append(data_tmp[i])
    #print(data[0:5])
    #print(np.array(data))
    return dates, np.array(data)

    

def read_temp_data_from_file(temp_file, delimiter='\t', encoding='utf-8'):
    fp = open( file = temp_file, 
               mode = 'r',
               encoding = encoding)
    tags = fp.readline().split(delimiter) # NOT USED

    lines = fp.readlines()
    dates = []
    data = []
    for line in lines:
        tmp = line.split(delimiter)
        dates.append(tmp[0])
        dtmp = []
        for i in range(1,len(tmp)):
            dtmp.append(float(tmp[i]))
        data.append(dtmp)

    fp.close()
    return dates, data

def seperate_data(dates, temp, ref_idx):
    tempref = temp[:,ref_idx]
    temp_aging = np.median(tempref[-3600:])
    i = 0
    dates_hb_data = dates[:52*3600]
    temp_hb_data = temp[:52*3600]
    while(1):
        temp_mean = np.median(tempref[-3600*(i+2):-3600*(i+1)])
        if abs(temp_mean-temp_aging)>3:
            break
        i += 1
    dates_aging_data = dates[-3600*(i+2):]
    temp_aging_data = temp[-3600*(i+2):]
    dates_cycle_data = dates[52*3600:-3600*(i+2)]
    temp_cycle_data = temp[52*3600:-3600*(i+2)]
    return dates_hb_data,temp_hb_data,dates_cycle_data,temp_cycle_data,dates_aging_data,temp_aging_data
        
def plot_temp(dates, temp, temp_idx, temp_lbs, marker_style,fname):
    timestamp=pd.to_datetime(dates)
    fig = plt.figure(figsize=(15,6))
    ax = plt.subplot(111)
    # ax.xaxis.set_major_formatter(mdate.DateFormatter('%m/%d %H:%M:%S'))
    ax.xaxis.set_major_formatter(mdate.DateFormatter('%m-%d %H:%M')) #指定时间显示的格式
    # plt.xticks(pd.date_range(timestamp[0], timestamp[-1], freq='S'), rotation=25)
    plt.xticks(pd.date_range(timestamp[0], timestamp[-1], freq='300min'), rotation=30)   #以4hrs为时钟间隔
    print("tempshape",temp.shape)
    for idx in temp_idx:
        # ax.plot(timestamp, temp[:,idx], linestyle=line_style[idx], label=temp_lbs[idx])
        ax.plot(timestamp, temp[:,idx], marker=marker_style[idx], markersize=3, linestyle='', label=temp_lbs[idx])
    
    t173 = 173*np.ones(len(timestamp))
    t358 = 358*np.ones(len(timestamp))
    ax.plot(timestamp, t173, color='b', lw=3, linestyle='dashed', label='173K')
    ax.plot(timestamp, t358, color='r', lw=3, linestyle='dashed', label='358K')
    ax.legend(loc='best', prop=font)
    ax.set_xlabel('Dates')
    ax.set_ylabel('Temp(K)')
    ax.grid()
    
    plt.tight_layout()
    plt.savefig(fname+'.png')
#    plt.show()


#################################################################################
# 这里的对应关系需要你自己再确认一遍
temp_lbs = [r'A', u'B', u'C1', u'C2', u'F24-21201-23-01-探测器1', u'', r'D1', r'D2', r'', r'']
#temp_idx = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
temp_idx = [4]
marker_style = ['d', 's', 'o', 'v', '^', '*', '*', 'd', 's', 'o']

if __name__=='__main__':
    dates, temp = read_temp_data_from_dir(sys.argv[1], encoding='iso-8859-1')
    dates_hb_data,temp_hb_data,dates_cycle_data,temp_cycle_data,dates_aging_data,\
                            temp_aging_data = seperate_data(dates, temp, 4)
    print("dates_hb_data",dates_hb_data)
 #   plot_temp(dates_hb_data, temp_hb_data, temp_idx=temp_idx, temp_lbs=temp_lbs, marker_style=marker_style, fname = sys.argv[2]+"_hb")
 #   plot_temp(dates_cycle_data, temp_cycle_data, temp_idx=temp_idx, temp_lbs=temp_lbs, marker_style=marker_style, fname = sys.argv[2]+"_cycle")
    plot_temp(dates_aging_data, temp_aging_data, temp_idx=temp_idx, temp_lbs=temp_lbs, marker_style=marker_style, fname = sys.argv[2]+"_aging")
    
#    plot_temp_diff(dates, temp, temp_idx=temp_idx, temp_lbs=temp_lbs, line_style=line_style)
    
    
